// pages/calculation/index.js
import {model} from './model.js';
var area = require('../../utils/area.js');
import WxValidate from '../../utils/WxValidate.js'
var Validate=null;
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
        areaList: area.default,
        current_city:'',
        select_address:false,
        textareaH:{
            maxHeight:100,
            minHeight:50
        },
        placeholder_style:"color:#999;",
        formData:{
            province:'',
            city:'',
        }
    },
    

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
        this.initValidate()
    },

    //验证函数
  initValidate: function () {
    const rules = {
      province:{
         required: true,
      },
      city:{
          required:true
      },  
      area: {
        required: true,
      },
      position: {
        required: true,
      },
      name: {
        required: true,
      },
      mobile: {
        required: true,
        tel:true
      }
    }
    const messages = {
        province:{
            required:"请选择城市"
        },
        city:{
            required:"请选择城市"
        },
      area: {
        required: '面积必填',
      },
      position: {
        required: '位置必填',
      },
      name:{
        required:'姓名必填'
      },
      mobile:{
        required:'手机必填',
        tel:"手机号格式错误"
      }
    }
    // 创建实例对象
    Validate = new WxValidate(rules,messages)
  },


    // 选择地址
  changeArea: function () {
    this.setData({ select_address: true })
  },

  // 关闭地址选择
  onClose: function () {
    this.setData({
      select_address: false
    });
  },

  onInput(e){
      let data=this.data.formData;
      let key=e.currentTarget.dataset.name;
      data[key]=e.detail;
      
      this.data.formData=data;
      console.log(this.data)
    // this.setData(data);
  },
  
  // 选择地址
  onSelectOk: function (e) {
    var detail = e.detail.values;

    var province=detail[0].name;
    var city=detail[1].name;
    let formData=this.data.formData;
        formData['province']=province;
        formData['city']=city;

    this.setData({
        formData,
      current_city:province+' / '+city
    });
    this.onClose();
  },

  onSubmit(){
      let formData=this.data.formData;
     //校验表单
     if (!Validate.checkForm(formData)) {
        var error = Validate.errorList[0]
        wx.showToast({
          title: error.msg,
          icon:'none'
        })
        return false
      }

      model.put(formData,(res)=>{
          if(res.data.code){
            wx.showToast({
                title: res.data.msg,
                icon: 'success',
            });
          }else{
            wx.showToast({
                title: res.data.msg,
                icon: 'none',
            });
          }
      },
      (res)=>{
          wx.showToast({
              title: res.data.msg,
              icon: 'none',
          });
            
      });

  },

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})